package kuzmenkov.oip.controller.applet;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.util.logging.Logger;

import javax.swing.JPanel;

/**
 * Class renders  a selected image
 * @author Michael Kuzmenkov
 *
 */
public class ImagePanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7033561425773020748L;

	private Logger log = Logger.getLogger(ImagePanel.class.getName());

	/**
	 * A rendered image
	 */
	private Image image;
	/**
	 * A width of a rendered image
	 */
	private int imgWidth;
	/**
	 * A height of a rendered image
	 */
	private int imgHeight;
	/**
	 * X-coordinate of the left top corner of a rendered image
	 */
	private int imgX;
	/**
	 * Y-coordinate of the left top corner of a rendered image
	 */
	private int imgY;
	/**
	 * An observer of a image loading 
	 */
	private ImageObserver imgObs = new ImageObserverImpl();

	public ImagePanel() {
		imgWidth  = 200;
		imgHeight = 200;

	}

	/**
	 * Sets the image which will be rendered
	 * @param image
	 */
	public void setImage(Image image) {
		this.image = image;
		repaint();
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;
		log.info("entry");
		if (image != null) {
			g2d.drawImage(image, imgX, imgY, imgWidth, imgHeight, imgObs);
		}
	}

	/**
	 * A observer of a image loading
	 * @author Michael Kuzmenkov
	 *
	 */
	class ImageObserverImpl implements ImageObserver {

		public boolean imageUpdate(Image img, int infoflags, int x, int y,
				int width, int height) {
			if (infoflags == ImageObserver.ALLBITS) {
				log.info("The image is successfully loaded");
				int panelHeight = ImagePanel.this.getHeight();
				int panelWidth = ImagePanel.this.getWidth();
				
				if (height>width){
					if(height>panelHeight){
						imgHeight = panelHeight;
						imgWidth = (width*panelHeight)/height;
						imgX = (panelWidth-imgWidth)/2;
						imgY=0;
					}
				} else {
					if (width>panelWidth){
						imgWidth = panelWidth;
						imgHeight = (height*panelWidth)/width;
						imgX = 0;
						imgY = (panelHeight-imgHeight)/2;
					}
				}
				
				log.info("panelHeight=" + panelHeight + ", height=" + height
						+ ", imgHeight" + imgHeight);
				
				log.info("panelWidth=" + panelWidth + ", width=" + width
						+ ", imgWidth" + imgWidth);

				ImagePanel.this.repaint();
				return false;
			}
			return true;
		}

	}

}
